﻿using Kingdee.BOS;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.ServiceHelper;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.Drawing;

namespace RK.MySchedule.GFT
{
    public class SendEMail : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            try
            {
                DataTable table = DBServiceHelper.ExecuteDataSet(ctx, "select FBTYPEID,FBRROCESS from AY_BAS_ReportType where FBTYPEID in (select FBTYPEID from AY_BAS_REPORTEMAIL)").Tables[0];
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    this.SendMail(ctx, schedule, Convert.ToInt32(table.Rows[i]["FBTYPEID"]), table.Rows[i]["FBRROCESS"].ToString());
                    Thread.Sleep(0xbb8);
                }
            }
            catch (Exception exception)
            {
                string str = "errorautomail.txt";
                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upload") + "/" + str;
                string directoryName = Path.GetDirectoryName(path);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write);
                StreamWriter writer = new StreamWriter(stream);
                writer.Write(DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") + "：" + exception);
                writer.Close();
                stream.Close();
                throw exception;
            }
        }

        private void SendMail(Context ctx, Schedule schedule, int FBTYPEId, string FBRROCESS)
        {
            string fileName = "";
            try
            {
                string str2 = "邮件通知";
                string str3 = "相关内容请查收附件!<br/>谢谢!";
                string str4 = "0";
                DataTable table = null;
                string str5 = "select  a.*,b.FMAILSERVER FMAILSERVERName,b.FSMTPPORT from AY_BAS_REPORTEMAIL a  left join T_BAS_MAILSERVER b on b.FID=a.FMAILSERVER where a.FBTYPEId=" + FBTYPEId;
                DataTable table2 = DBServiceHelper.ExecuteDataSet(ctx, str5).Tables[0];
                string displayName = "";
                string userName = "";
                string password = "";
                string address = "";
                string str10 = "";
                int num = 0x19;
                if (table2.Rows.Count != 0)
                {
                    if (table2.Rows.Count > 0)
                    {
                        str2 = table2.Rows[0]["FTITLE"].ToString();
                        str4 = table2.Rows[0]["FID"].ToString();
                        displayName = table2.Rows[0]["FACCOUNT"].ToString();
                        userName = table2.Rows[0]["FUSERNAME"].ToString();
                        password = table2.Rows[0]["FPASSWORD"].ToString();
                        address = table2.Rows[0]["FEMAILADDRESS"].ToString();
                        str10 = table2.Rows[0]["FMAILSERVERName"].ToString();
                        num = Convert.ToInt32(table2.Rows[0]["FSMTPPORT"]);
                    }
                    table = DBServiceHelper.ExecuteDataSet(ctx, " select  * from  AY_BAS_REPORTEMAIL_D  where FID=" + str4).Tables[0];
                    if (table.Rows.Count != 0)
                    {
                        fileName = this.ExportExcel(ctx, schedule, FBRROCESS);
                        if ((fileName != "") && !fileName.Equals(""))
                        {
                            MailMessage message = new MailMessage();
                            SmtpClient client = new SmtpClient();
                            message.From = new MailAddress(address, displayName, Encoding.UTF8);
                            Attachment item = new Attachment(fileName)
                            {
                                Name = str2 + "_" + DateTime.Now.ToLocalTime().ToString("yyyyMMdd") + ".xls"
                            };
                            message.Attachments.Add(item);
                            for (int i = 0; i < table.Rows.Count; i++)
                            {
                                message.To.Add(new MailAddress(table.Rows[i]["FEMAIL"].ToString()));
                            }
                            message.IsBodyHtml = true;
                            message.SubjectEncoding = Encoding.UTF8;
                            message.Subject = str2;
                            message.BodyEncoding = Encoding.UTF8;
                            message.Priority = MailPriority.Normal;
                            message.Body = str3;
                            client.Host = str10;
                            client.DeliveryMethod = SmtpDeliveryMethod.Network;
                            client.Timeout = 0xf4240;
                            client.EnableSsl = false;
                            client.Port = num;
                            client.UseDefaultCredentials = true;
                            client.Credentials = new NetworkCredential(userName, password);
                            client.Send(message);
                            Thread.Sleep(0x1f40);
                            item.Dispose();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                if (!fileName.Equals(""))
                {
                    File.Delete(fileName);
                }
            }
        }

        private string ExportExcel(Context ctx, Schedule schedule, string sql)
        {
            try
            {
                int num4;
                string str = DateTime.Now.ToLocalTime().ToString("yyyyMMddHHmmss") + "report.xls";
                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upload") + "/" + str;
                string directoryName = Path.GetDirectoryName(path);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                DataTable table = DBServiceHelper.ExecuteDataSet(ctx, "exec " + sql).Tables[0];
                FileStream newStream = new FileStream(path, FileMode.Create);
                ExcelPackage package = new ExcelPackage(newStream);
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("单据体");
                int row = 1;
                int num2 = 1;
                int[] numArray = new int[table.Columns.Count];
                for (num4 = 0; num4 < table.Columns.Count; num4++)
                {
                    worksheet.Cells[row, num2 + num4].Value = table.Columns[num4].ColumnName;
                    worksheet.Column(num2 + num4).AutoFit();
                }
                worksheet.Row(row).Style.Font.Bold = true;
                row++;
                for (num4 = 0; num4 < table.Rows.Count; num4++)
                {
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        if (numArray[i] == 0)
                        {
                            numArray[i] = Encoding.Default.GetBytes(table.Rows[num4][i].ToString()).Length;
                        }
                        worksheet.Cells[row + num4, num2 + i].Value = table.Rows[num4][i].ToString();
                        if (Encoding.Default.GetBytes(table.Rows[num4][i].ToString()).Length > numArray[i])
                        {
                            numArray[i] = Encoding.Default.GetBytes(table.Rows[num4][i].ToString()).Length;
                        }
                        if (num4 == (table.Rows.Count - 1))
                        {
                            if (numArray[i] > 0x19)
                            {
                                worksheet.Column(num2 + i).Width = 30.0;
                            }
                            else
                            {
                                worksheet.Column(num2 + i).AutoFit();
                            }
                        }
                    }
                }
                worksheet.Cells.Style.Font.Name = "Arial";
                worksheet.Cells.Style.Font.Size = 11f;
                worksheet.Row(1).Style.Fill.PatternType = ExcelFillStyle.Solid;
                worksheet.Row(1).Style.Fill.BackgroundColor.SetColor(Color.Gainsboro);
                worksheet.Cells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                worksheet.Cells.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                worksheet.Cells.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                worksheet.Cells.Style.Border.Right.Style = ExcelBorderStyle.Thin;
                worksheet.Row(1).Style.Border.Top.Style = ExcelBorderStyle.Thin;
                worksheet.Row(1).Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                worksheet.Row(1).Style.Border.Left.Style = ExcelBorderStyle.Thin;
                worksheet.Row(1).Style.Border.Right.Style = ExcelBorderStyle.Thin;
                worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                worksheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                worksheet.Cells.Style.WrapText = true;
                worksheet.Cells.Style.Numberformat.Format = "@";
                package.Save();
                newStream.Close();
                newStream.Dispose();
                package.Dispose();
                return path;
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}
